<?php

/**
 *      [Discuz!] (C)2001-2099 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: spacecp_usergroup.php 6790 2010-03-25 12:30:53Z cnteacher $
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

require_once libfile('function/forumlist');
$switchmaingroup = $_G['group']['grouppublic'] || $_G['group']['grouptype'] == 'member' ? 1 : 0;
$extgroupidarray = $_G['forum_extgroupids'] ? explode("\t", $_G['forum_extgroupids']) : array();
foreach($extgroupidarray as $key => $val) {
	$val = intval($val);
	if($val <  1) {
		unset($extgroupidarray[$key]);
	} else {
		$extgroupidarray[$key] = intval($val);
	}
}
if(implode("\t", $extgroupidarray) != $_G['forum_extgroupids']) {
	$_G['forum_extgroupids'] = implode("\t", $extgroupidarray);
	$groupexpiryadd= empty($_G['forum_extgroupids']) ? ", groupexpiry=''" : '';
	DB::query("UPDATE ".DB::table('common_member')." SET extgroupids='".$_G['forum_extgroupids']."' $groupexpiryadd WHERE uid='$_G[uid]'");
}

if(empty($type)) {

	$groupterms = unserialize(DB::result_first("SELECT groupterms FROM ".DB::table('common_member_field_forum')." WHERE uid='$_G[uid]'"));

	$maingroup = $extgroups = $publicgroups = $grouplist = array();

	$query = DB::query("SELECT * FROM ".DB::table('common_usergroup')." WHERE (type='special' AND system<>'private' AND radminid='0') OR (type='member' AND '".$_G['member']['credits']."'>=creditshigher AND '".$_G['member']['credits']."'<creditslower) OR groupid IN ('$_G[groupid]'".($_G['forum_extgroupids'] ? ', '.str_replace("\t", ',', $_G['forum_extgroupids']) : '').") ORDER BY type, system");
	while($group = DB::fetch($query)) {

		if(!$group['allowmultigroups']) {
			$group['grouptitle'] = '<u>'.$group['grouptitle'].'</u>';
		}

		$group['mainselected'] = $group['groupid'] == $_G['groupid'] ? 'checked="checked"' : '';
		$group['maindisabled'] = $switchmaingroup && (($group['system'] != 'private' && ($group['system'] == "0\t0" || $group['groupid'] == $_G['groupid'] || in_array($group['groupid'], $extgroupidarray))) || $group['type'] == 'member') ? '' : 'disabled';
		$group['allowsetmain'] = $switchmaingroup && (($group['system'] != 'private' && ($group['system'] == "0\t0" || $group['groupid'] == $_G['groupid'] || in_array($group['groupid'], $extgroupidarray))) || $group['type'] == 'member') ? true : false;
		$group['dailyprice'] = $group['minspan'] = 0;

		if($group['system'] != 'private') {
			list($group['dailyprice'], $group['minspan']) = explode("\t", $group['system']);
		}

		if($group['groupid'] == $_G['groupid'] && !empty($groupterms['main'])) {
			$group['expiry'] = dgmdate($groupterms['main']['time'], 'd');
		} elseif(isset($groupterms['ext'][$group['groupid']])) {
			$group['expiry'] = dgmdate($groupterms['ext'][$group['groupid']], 'd');
		} else {
			$group['expiry'] = '-';
		}

		if($group['groupid'] == $_G['groupid']) {
			$maingroup = $group;
			$group['owned'] = true;
		} elseif(in_array($group['groupid'], $extgroupidarray)) {
			$extgroups[] = $group;
			$group['owned'] = true;
		} else {
			$group['owned'] = false;
		}

		if($group['system'] != 'private') {
			$publicgroups[$group['groupid']] = $group;
		}

	}

	$query = DB::query("SELECT * FROM ".DB::table('common_usergroup')." WHERE type!='system' ORDER BY type, creditshigher");
	while($group = DB::fetch($query)) {
		$group['type'] = $group['type'] == 'special' && $group['radminid'] ? 'specialadmin' : $group['type'];
		$grouplist[$group['type']][] = $group;
	}

	include template("home/spacecp_usergroup");

} else {

	if($type == 'main' && $switchmaingroup) {


		$edit = intval($edit);
		$group = DB::fetch_first("SELECT groupid, type, system, grouptitle, allowmultigroups FROM ".DB::table('common_usergroup')." WHERE groupid='$edit' AND (".($_G['forum_extgroupids'] ? 'groupid IN ('.str_replace("\t", ',', $_G['forum_extgroupids']).') OR ' : '')."(type='special' AND system='0\t0' AND radminid='0') OR (type='member' AND '".$_G['member']['credits']."'>=creditshigher AND '".$_G['member']['credits']."'<creditslower))");
		if(!$group) {
			showmessage('undefined_action', NULL);
		}

		if(!submitcheck('groupsubmit')) {
			include template('forum/memcp_usergroups_misc');
			dexit();
		}

		$extgroupidsnew = $_G['groupid'];
		foreach(explode("\t", $_G['forum_extgroupids']) as $extgroupid) {
			if($extgroupid && $extgroupid != $edit) {
				$extgroupidsnew .= "\t".$extgroupid;
			}
		}
		$adminidnew = in_array($_G['adminid'], array(1, 2, 3)) ? $_G['adminid'] : ($group['type'] == 'special' ? -1 : 0);

		DB::query("UPDATE ".DB::table('common_member')." SET groupid='$edit', adminid='$adminidnew', extgroupids='$extgroupidsnew' WHERE uid='$_G[uid]'");
		showmessage('usergroups_update_succeed', 'forum.php?mod=memcp&action=usergroups');


	} elseif($type == 'extended') {


		$group = DB::fetch_first("SELECT groupid, type, system, grouptitle FROM ".DB::table('common_usergroup')." WHERE groupid='$edit' AND (".($_G['forum_extgroupids'] ? 'groupid IN ('.str_replace("\t", ',', $_G['forum_extgroupids']).') OR ' : '')."(type='special' AND system<>'private' AND radminid='0'))");
		if(!$group) {
			showmessage('undefined_action', NULL);
		}

		$join = !in_array($group['groupid'], explode("\t", $_G['forum_extgroupids']));
		$group['dailyprice'] = $group['minspan'] = 0;

		if($group['system'] != 'private') {
			list($group['dailyprice'], $group['minspan']) = explode("\t", $group['system']);
			if($group['dailyprice'] > -1 && $group['minspan'] == 0) {
				 $group['minspan'] = 1;
			}
		}

		if(!isset($_G['setting']['extcredits'][$_G['setting']['creditstrans']])) {
			showmessage('credits_transaction_disabled');
		}

		if(!submitcheck('groupsubmit')) {

			$usermoney = getuserprofile('extcredits'.$_G['setting']['creditstrans']);
			$usermaxdays = $group['dailyprice'] > 0 ? round($usermoney / $group['dailyprice']) : 0;
			$group['minamount'] = $group['dailyprice'] * $group['minspan'];

			include template('forum/memcp_usergroups_misc');

		} else {

			$groupterms = unserialize(DB::result_first("SELECT groupterms FROM ".DB::table('common_member_field_forum')." WHERE uid='$_G[uid]'"));

			if($join) {

				$extgroupidsarray = array();
				foreach(array_unique(array_merge(explode("\t", $_G['forum_extgroupids']), array($edit))) as $extgroupid) {
					if($extgroupid) {
						$extgroupidsarray[] = $extgroupid;
					}
				}
				$extgroupidsnew = implode("\t", $extgroupidsarray);

				if($group['dailyprice']) {
					if(($days = intval($days)) < $group['minspan']) {
						showmessage('usergroups_span_invalid', '', array('minspan' => $group['minspan']));
					}

					if(getuserprofile('extcredits'.$_G['setting']['creditstrans']) - ($amount = $days * $group['dailyprice']) < ($minbalance = 0)) {
						showmessage('credits_balance_insufficient', '', array($minbalance));
					}

					$groupexpirynew = TIMESTAMP + $days * 86400;
					$groupterms['ext'][$edit] = $groupexpirynew;

					$groupexpirynew = groupexpiry($groupterms);

					DB::query("UPDATE ".DB::table('common_member')." SET groupexpiry='$groupexpirynew', extgroupids='$extgroupidsnew', extcredits".$_G['setting']['creditstrans']."=extcredits".$_G['setting']['creditstrans']."-'$amount' WHERE uid='$_G[uid]'");
					DB::query("UPDATE ".DB::table('common_member_field_forum')." SET groupterms='".addslashes(serialize($groupterms))."' WHERE uid='$_G[uid]'");
					DB::query("INSERT INTO ".DB::table('common_creditlog')." (uid, fromto, sendcredits, receivecredits, send, receive, dateline, operation)
						VALUES ('$_G[uid]', '$_G[username]', '".$_G['setting']['creditstrans']."', '0', '$amount', '0', '$_G[timestamp]', 'UGP')");
				} else {
					DB::query("UPDATE ".DB::table('common_member')." SET extgroupids='$extgroupidsnew' WHERE uid='$_G[uid]'");
				}

				showmessage('usergroups_join_succeed', 'forum.php?mod=memcp&action=usergroups');

			} else {

				if($edit != $_G['groupid']) {
					if(isset($groupterms['ext'][$edit])) {
						unset($groupterms['ext'][$edit]);
					}
					$groupexpirynew = groupexpiry($groupterms);
					DB::query("UPDATE ".DB::table('common_member_field_forum')." SET groupterms='".addslashes(serialize($groupterms))."' WHERE uid='$_G[uid]'");
				} else {
					$groupexpirynew = 'groupexpiry';
				}

				$extgroupidsarray = array();
				foreach(explode("\t", $_G['forum_extgroupids']) as $extgroupid) {
					if($extgroupid && $extgroupid != $edit) {
						$extgroupidsarray[] = $extgroupid;
					}
				}
				$extgroupidsnew = implode("\t", array_unique($extgroupidsarray));
				DB::query("UPDATE ".DB::table('common_member')." SET groupexpiry='$groupexpirynew', extgroupids='$extgroupidsnew' WHERE uid='$_G[uid]'");

				showmessage('usergroups_exit_succeed', 'forum.php?mod=memcp&action=usergroups');

			}

		}

	} else {

		showmessage('usergroups_nonexistence');

	}

}


?>